package com.taofengsdk.video.core;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.taofengsdk.adutil.Utils;
import com.taofengsdk.constant.SDKConstant;
import com.taofengsdk.model.AdValue;
import com.taofengsdk.video.activity.AdBrowserActivity;
import com.taofengsdk.video.parameters.AdParameters;
import com.taofengsdk.video.report.ReportManager;
import com.taofengsdk.widegt.CustomVideoView;
import com.taofengsdk.widegt.CustomVideoView.ADVideoPlayerListener;
import com.taofengsdk.widegt.VideoFullDialog;

/**
 * Created by tao on 17-3-16.
 *
 * @function 业务逻辑层
 */

public class VideoAdSlot implements ADVideoPlayerListener {
    private Context mContext;
    /**
     * UI
     */
    private CustomVideoView mVideoView;
    private ViewGroup mParentView;  //要添加到父容器中
    /**
     * Data
     */
    private AdValue mVideoInfo;
    private AdSDKSlotListener mSlotListener;
    private boolean mIsCanPause = false; //是否能够自动暂停标志位
    private int lastArea = 0;


    public VideoAdSlot(AdValue adInstance, AdSDKSlotListener slotListener,
                       CustomVideoView.ADFrameImageLoadListener frameImageLoadListener) {
        this.mVideoInfo = adInstance;
        mSlotListener = slotListener;
        mParentView = slotListener.getAdParent();
        mContext = mParentView.getContext();

        initVideoView(frameImageLoadListener);
    }

    private void initVideoView(CustomVideoView.ADFrameImageLoadListener frameImageLoadListener) {
        mVideoView = new CustomVideoView(mContext, mParentView);
        if (mVideoInfo != null) {
            mVideoView.setDataSource(mVideoInfo.resource);
            mVideoView.setFrameURI(mVideoInfo.thumb);
            mVideoView.setAdvideoPlayListener(this);
            mVideoView.setFrameLoadListener(frameImageLoadListener);
        }
        RelativeLayout paddingView = new RelativeLayout(mContext);
        paddingView.setBackgroundColor(mContext.getResources().getColor(android.R.color.black));
        paddingView.setLayoutParams(mVideoView.getLayoutParams());
        mParentView.addView(paddingView);
        mParentView.addView(mVideoView);
    }

    /**
     * 实现滑入播放,画出暂停
     */
    public void updateVideoInScrollView() {
        //获取当前的video的屏幕在手机上出现的百分比
        int currentArea = Utils.getVisiblePercent(mParentView);
        //没有出现在屏幕上,不做任何处理
        if (currentArea <= SDKConstant.VIDEO_ZERO_PERCENT) {
            return;
        }
        //如果刚要滑出和滑进的时候的异常处理
        if (Math.abs(currentArea - lastArea) >= SDKConstant.VIDEO_ONE_HUNDRED_PERCENT) {
            return;
        }

        if (currentArea <= SDKConstant.VIDEO_SCREEN_PERCENT) {
            if (isCanPause()) {
                pauseVideo(true);
                setIsCanPause(false);//事件过滤
                lastArea = 0;
                mVideoView.setIsRealPause(false);
                mVideoView.setIsComplete(false);
            }

            return;
        }
        //当视频真正暂停时
        if (isRealPause() || isComplete()) {
            pauseVideo(false);
            setIsCanPause(false);

            return;
        }
        //满足用户的视频播放设置条件
        if (Utils.canAutoPlay(mContext, AdParameters.getCurrentSetting()) || isPlaying()) {
            //满足条件播放视频
            lastArea = currentArea;
            resumeVideo();
            setIsCanPause(true);
            mVideoView.setIsRealPause(false);

        } else {
            pauseVideo(false);
            mVideoView.setIsRealPause(true);
        }

    }

    public void destory() {
        mVideoView.destory();
        mVideoView = null;
        mContext = null;
        mVideoInfo = null;
    }

    @Override
    public void onBufferUpdate(int time) {
        try {
            ReportManager.suReport(mVideoInfo.middleMonitor, time / SDKConstant.MILLION_UNIT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 实现小屏到全屏的播放功能接口
     */
    @Override
    public void onClickFullScreenBtn() {
        try {
            ReportManager.fullScreenReport(mVideoInfo.event.full.content, getPosition());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取videoview在当前界面的属性
        Bundle bundle = Utils.getViewProperty(mParentView);
        mParentView.removeView(mVideoView);

        VideoFullDialog dialog = new VideoFullDialog(mContext, mVideoView, mVideoInfo, getPosition());
        dialog.setFullToSmallListener(new VideoFullDialog.FullToSmallListener() {
            @Override
            public void getCurrentPlayPosition(int position) {
                backToSmallPlay(position);
            }

            @Override
            public void onVideoPlayComplete() {
                FullPlayComplete();
            }
        });
        dialog.setViewBundle(bundle); //为Dialog设置播放器数据Bundle对象
        dialog.setSlotListener(mSlotListener);
        dialog.show();
    }

    /**
     * 返回小屏的时候
     *
     * @param position
     */
    private void backToSmallPlay(int position) {
        if (mVideoView.getParent() == null) {
            mParentView.addView(mVideoView);
        }
        if (isPlaying()) {
            mVideoView.setTranslationY(0); //防止动画导致偏离父容器
            mVideoView.setIsMute(true);
            mVideoView.setAdvideoPlayListener(this);
            mVideoView.seekAndResume(position);
            setIsCanPause(true);
        } else {
            mVideoView.setIsMute(false);
            mVideoView.setAdvideoPlayListener(this);
            mVideoView.seekAndPause(position);
            setIsCanPause(false);
        }
    }

    public void FullPlayComplete() {
        //是否存在Parent
        if (mVideoView.getParent() == null) {
            mParentView.addView(mVideoView);
        }
        mVideoView.setTranslationY(0); //防止动画导致偏离父容器
        mVideoView.isShowFullBtn(true);
        mVideoView.setIsMute(true);
        mVideoView.setAdvideoPlayListener(this);
        mVideoView.seekAndPause(0);
        setIsCanPause(false);
    }

    public void changeFagmentOrActivity() {
        if (isPlaying()) {
            pauseVideo(false);
        }
    }

    @Override
    public void onClickVideo() {
//        String desationUrl = mVideoInfo.clickUrl;
//        if (mSlotListener != null) {
//            if (mVideoView.isFrameHidden() && !TextUtils.isEmpty(desationUrl)) {
//                mSlotListener.onClickVideo(desationUrl);
//                try {
//                    ReportManager.pauseVideoReport(mVideoInfo.clickMonitor, mVideoView.getCurrentPosition()
//                            / SDKConstant.MILLION_UNIT);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        } else {
//            //走默认样式
//            if (mVideoView.isFrameHidden() && !TextUtils.isEmpty(desationUrl)) {
//                Intent intent = new Intent(mContext, AdBrowserActivity.class);
//                intent.putExtra(AdBrowserActivity.KEY_URL, mVideoInfo.clickUrl);
//                mContext.startActivity(intent);
//                try {
//                    ReportManager.pauseVideoReport(mVideoInfo.clickMonitor, mVideoView.getCurrentPosition()
//                            / SDKConstant.MILLION_UNIT);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
    }

    @Override
    public void onClickBackBtn() {

    }

    @Override
    public void onClickPlay() {
        sendSUSReport(false);
    }

    @Override
    public void onAdVideoLoadSuccess() {
        if (mSlotListener != null) {
            mSlotListener.onAdVideoLoadSuccess();
        }
    }

    @Override
    public void onAdVideoLoadFailed() {
        if (mSlotListener != null) {
            mSlotListener.onAdVideoLoadFailed();
        }
    }


    @Override
    public void onAdVideoLoadComplete() {
        try {
            ReportManager.sueReport(mVideoInfo.endMonitor, false, getDuration());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mSlotListener != null) {
            mSlotListener.onAdVideoLoadComplete();
        }
        mVideoView.setIsRealPause(true);
    }

    private void setIsCanPause(boolean isCanPause) {
        mIsCanPause = isCanPause;
    }

    private boolean isCanPause() {
        return mIsCanPause;
    }

    private int getPosition() {
        return mVideoView.getCurrentPosition() / SDKConstant.MILLION_UNIT;
    }

    private int getDuration() {
        return mVideoView.getDuration() / SDKConstant.MILLION_UNIT;
    }

    private boolean isPlaying() {
        return mVideoView.isPlaying();
    }

    private boolean isRealPause() {
        return mVideoView.isRealPause();
    }

    private boolean isComplete() {
        return mVideoView.isComplete();
    }

    private void pauseVideo(boolean isAuto) {
        if (mVideoView != null) {
            if (isAuto) {
                //发自动暂停监测
                if (!isRealPause() && isPlaying()) {
                    try {
                        ReportManager.pauseVideoReport(mVideoInfo.event.pause.content, getPosition());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            mVideoView.seekAndPause(0);
        }
    }

    private void resumeVideo() {
        if (mVideoView != null) {
            mVideoView.seekAndResume(getPosition());
            if (isPlaying()) {
                sendSUSReport(true); //发自动播放监测
            }
        }
    }

    /**
     * 发送视频开始播放监测
     *
     * @param isAuto
     */
    private void sendSUSReport(boolean isAuto) {
        try {
            ReportManager.susReport(mVideoInfo.startMonitor, isAuto);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //传递消息到appcontext层
    public interface AdSDKSlotListener {

        public ViewGroup getAdParent();

        public void onAdVideoLoadSuccess();

        public void onAdVideoLoadFailed();

        public void onAdVideoLoadComplete();

        public void onClickVideo(String url);

        void changeFagmentOrActivity();
    }
}
